package com.thingsgrid.basicInterface.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.thingsgrid.basicInterface.entity.ApiInterfaceTypeRelation;
import com.thingsgrid.basicInterface.entity.BasicInterface;
import com.thingsgrid.basicInterface.service.IApiInterfaceTypeRelationService;
import com.thingsgrid.basicInterface.service.IBasicInterfaceService;
import com.thingsgrid.basicInterface.vo.TypeChild;
import com.thingsgrid.basicInterface.vo.TypeTree;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.cms.PasswordRecipientId;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.thingsgrid.basicInterface.entity.BasicInterfaceType;
import com.thingsgrid.basicInterface.vo.BasicInterfaceTypeVO;
import com.thingsgrid.basicInterface.wrapper.BasicInterfaceTypeWrapper;
import com.thingsgrid.basicInterface.service.IBasicInterfaceTypeService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.*;
import java.util.stream.Collectors;

/**
 *  控制器
 *
 * @author BladeX
 * @since 2019-08-10
 */
@RestController
@AllArgsConstructor
@RequestMapping("/test/basicinterfacetype")
@Validated
@Api(value = "基础接口微服务", tags = "接口类型")
public class BasicInterfaceTypeController extends BladeController {

	private IBasicInterfaceTypeService basicInterfaceTypeService;

	private IBasicInterfaceService basicInterfaceService;

	private IApiInterfaceTypeRelationService apiInterfaceTypeRelationService;

	/**
	* 详情
	*/
	@GetMapping("/detail")
    @ApiOperationSupport(order = 1)
	@ApiOperation(value = "接口类型详情")
	@ApiImplicitParam(name = "id", value = "接口类型ID", paramType = "query", dataType = "Long",required = true)
	public R<Object> detail(BasicInterfaceType basicInterfaceType) {
		BasicInterfaceType detail = basicInterfaceTypeService.getOne(Condition.getQueryWrapper(basicInterfaceType));
		BasicInterfaceTypeVO basicInterfaceTypeVO = BasicInterfaceTypeWrapper.build().entityVO(detail);
		HashMap<String, Object> map = new HashMap<>();
		map.put("type",basicInterfaceTypeVO);
		if("0".equals(basicInterfaceTypeVO.getCategory())){
			List<BasicInterface> list = basicInterfaceService.list(new LambdaQueryWrapper<BasicInterface>().eq(BasicInterface::getTypeId, basicInterfaceType.getId()));
			map.put("apiList",list);
		}else {
			List<Long> apiIds = apiInterfaceTypeRelationService.getApiIds(basicInterfaceType.getId());
			Collection<BasicInterface> basicInterfaces = new ArrayList<BasicInterface>();
			map.put("apiList",basicInterfaces);
			if(!apiIds.isEmpty()){
				basicInterfaces = basicInterfaceService.listByIds(apiIds);
				map.put("apiList",basicInterfaces);
			}
		}
		return R.data(map);
	}

	/**
	* 分页 
	*/
	@GetMapping("/list")
    @ApiOperationSupport(order = 2)
	@ApiImplicitParams({
		@ApiImplicitParam(name = "typeName", value = "类型名称", paramType = "query", dataType = "string",required = false),
		@ApiImplicitParam(name = "category", value = "类型别类", paramType = "query", dataType = "string",required = false),
		@ApiImplicitParam(name = "current", value = "当前页码", paramType = "query", dataType = "int",required = false,defaultValue = "1"),
		@ApiImplicitParam(name = "size", value = "每页显示条数", paramType = "query", dataType = "int",required = false,defaultValue = "10")
	})
	@ApiOperation(value = "接口类型列表分页")
	public R<IPage<BasicInterfaceTypeVO>> list(BasicInterfaceType basicInterfaceType, Query query) {

		IPage<BasicInterfaceType> pages = basicInterfaceTypeService.page(Condition.getPage(query), Condition.getQueryWrapper(basicInterfaceType));
		BasicInterfaceTypeWrapper build = BasicInterfaceTypeWrapper.build();
		IPage<BasicInterfaceTypeVO> basicInterfaceTypeVOIPage = build.pageVO(pages);
		R<IPage<BasicInterfaceTypeVO>> data = R.data(basicInterfaceTypeVOIPage);
		return data;
	}

	/**
	* 新增或修改 
	*/
	@PostMapping("/submit")
    @ApiOperationSupport(order = 3)
	@ApiOperation(value = "接口类型新增或修改", notes = "传入basicInterfaceType")
	public R submit(@Validated @RequestBody BasicInterfaceType basicInterfaceType) {

		if(null == basicInterfaceType.getId()){
			BasicInterfaceType one = basicInterfaceTypeService.getOne(new LambdaQueryWrapper<BasicInterfaceType>()
				.eq(BasicInterfaceType::getTypeName, basicInterfaceType.getTypeName()));
			if(one != null){
				throw  new ApiException("接口类型已存在");
			}
		}

		return R.status(basicInterfaceTypeService.saveOrUpdate(basicInterfaceType));
	}

	
	/**
	* 逻辑删除
	*/
	@PostMapping("/remove")
    @ApiOperationSupport(order = 4)
	@ApiOperation(value = "接口类型删除", notes = "传入ids")
	public R remove(@ApiParam(value = "接口类型id字符串拼接", required = true) @RequestParam String ids) {
		List<Long> longs = Func.toLongList(ids);
		for(Long typeId : longs){
			int count = basicInterfaceService.count(new LambdaQueryWrapper<BasicInterface>()
				.eq(BasicInterface::getTypeId, typeId));
			if(count > 0)   throw new ApiException("接口类型下存在接口，无法删除");
		}
		return R.status(basicInterfaceTypeService.removeByIds(longs));
	}


	/**
	 * 权限包配置
	 *
	 */
	@GetMapping("/type/config")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "权限包配置查看")
	public R<List<TypeTree>> detail(Long id) {
		List<Long> apiIds = apiInterfaceTypeRelationService.getApiIds(id);
		List<TypeTree> typeTrees = apiInterfaceTypeRelationService.getTypeTrees(apiIds);
/*		List<BasicInterfaceType> types = basicInterfaceTypeService.list(new LambdaQueryWrapper<BasicInterfaceType>().eq(BasicInterfaceType::getCategory, "0"));
			List<TypeTree> typeTrees = types.stream().map(e -> new TypeTree(e)).collect(Collectors.toList());
		for (TypeTree type : typeTrees){
			List<BasicInterface> apiList = basicInterfaceService.list(new LambdaQueryWrapper<BasicInterface>().eq(BasicInterface::getTypeId, type.getId()));
			List<TypeChild> typeChildren = apiList.stream().map(e -> new TypeChild(e,apiIds)).collect(Collectors.toList());
			type.setChildren(typeChildren);
		}*/

		return R.data(typeTrees);

	}

	/**
	 * 权限包配置提交
	 *
	 */
	@PostMapping("/type/configSubmit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "权限包配置接口")
	public R detail(String typeId , String ids) {

		boolean remove = apiInterfaceTypeRelationService.remove(new LambdaQueryWrapper<ApiInterfaceTypeRelation>()
			.eq(ApiInterfaceTypeRelation::getTypeId, Long.parseLong(typeId.trim())));

		String[] apiIds = ids.trim().split(",");
		List<ApiInterfaceTypeRelation> ApiInterfaceTypeRelations = Arrays.asList(apiIds).stream().map(e -> ApiInterfaceTypeRelation.builder().apiId(Long.parseLong(e))
			.typeId(Long.parseLong(typeId.trim())).build()).collect(Collectors.toList());
		boolean b = apiInterfaceTypeRelationService.saveOrUpdateBatch(ApiInterfaceTypeRelations);

		return R.status(b);
	}


}
